package com.atguigu.yygh.oss.service.impl;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyuncs.exceptions.ClientException;
import com.atguigu.yygh.oss.properties.AliyunOssProperties;
import com.atguigu.yygh.oss.service.FileService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2025/3/21 22:19
 */
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private AliyunOssProperties aliyunOssProperties;
    @Override
    public String upload(MultipartFile file) throws ClientException, IOException {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = aliyunOssProperties.getEndpoint();
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填写Bucket名称，例如examplebucket。
        String bucketName = aliyunOssProperties.getBucketname();
        // 填写网络流地址。
        String url = "https://www.aliyun.com/";
        // 填写Bucket所在地域。以华东1（杭州）为例，Region填写为cn-hangzhou。
        String region = "cn-hangzhou";
        // 创建OSSClient实例。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();
        // 上传文件到OSS。
        String filename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        filename=uuid+filename;
        String timeUrl = new DateTime().toString("yyyy/MM/dd");
        filename=timeUrl+"/"+filename;
        // 上传文件流
        ossClient.putObject(bucketName,filename,file.getInputStream());
        // 关闭OSSClient。
        ossClient.shutdown();
        // 返回文件访问地址。
        //上传之后文件路径
        // https://yygh-atguigu.oss-cn-beijing.aliyuncs.com/01.jpg
        return "https://"+bucketName+"."+endpoint+"/"+filename;
    }
}
